﻿// -----------------------------------------------------------------------
// <copyright file="StronglyTypedCollectionProducer.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System.Threading.Tasks;
using Dhgms.TplHelper.Extensions;

namespace Dhgms.TplHelper.Model.DataReaderProducer
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Text;

    using Dhgms.TplHelper.Model.Info;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    /// <remarks>
    /// Based upon:
    /// "How to: Implement CopyToDataTable Where the Generic Type T Is Not a DataRow"
    /// http://msdn.microsoft.com/en-us/library/bb669096.aspx
    /// </remarks>
    public class StronglyTypedCollectionProducer<TInfoClass> : DataReaderProducerBase<TInfoClass>
        where TInfoClass : Dhgms.DataManager.Model.Info.InfoBase<TInfoClass>
    {
        private readonly DataTable dataTable;

        public StronglyTypedCollectionProducer(IEnumerable<TInfoClass> informationCollection)
        {
            if (informationCollection == null)
            {
                throw new ArgumentNullException("informationCollection");
            }

            dataTable = LinqExtensions.CopyToDataTable(informationCollection);
            // hack: until we change object shredder
            dataTable.Columns.Remove("HeaderRecord");
        }

        public override Task<DataRetrievalProcessorResult<TInfoClass>> ProduceAndConsume(
            Func<IDataReader, Task<DataRetrievalProcessorResult<TInfoClass>>> consumingAction)
        {
            if (consumingAction == null)
            {
                throw new ArgumentNullException("consumingAction");
            }

            var dataReader = dataTable.CreateDataReader();
            return consumingAction(dataReader);
        }
    }
}
